﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace EzDesk.Utility.Json
{
    public static class JsonHelper
    {
        public static string ConvertToJson(object source)
        {
            return JsonConvert.SerializeObject(source, Formatting.Indented,new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
        }

        public static string ConvertToJson<T>(T source)
        {
            return JsonConvert.SerializeObject(source, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
        }

        public static Dictionary<string, string> JsonToDictionary(string jsonStr)
        {
            if (String.IsNullOrEmpty(jsonStr))
            {
                return new Dictionary<string, string>();
            }
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JsonConvert.PopulateObject(jsonStr, dic);
            return dic;
        }
        public static T JsonTo<T>(string jsonStr) where T : new()
        {
            T result = new T();
            if (String.IsNullOrEmpty(jsonStr))
            {
                return result;
            }

            JsonConvert.PopulateObject(jsonStr, result);
            return result;
        }

    }
}
